package com.jewelry.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jewelry.entity.Comment;
import com.jewelry.entity.Order;
import com.jewelry.entity.OrderItem;
import com.jewelry.mapper.CommentMapper;
import com.jewelry.service.CommentService;
import com.jewelry.service.OrderItemService;
import com.jewelry.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("comm")
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private OrderService orderService;


    @GetMapping("byId")
    private List<Comment> showById(Integer productId) {
        System.out.println("-----------------------");
        System.out.println(productId);
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("p_id", productId);
        List<Comment> comments = commentMapper.selectList(queryWrapper);
        return comments;
    }

    @GetMapping("byOrderId/{orderId}")
    private String showByOrderId(@PathVariable(value = "orderId") Long orderId) {
        Comment comment = commentService.lambdaQuery().eq(Comment::getOrderId, orderId).one();
        if(ObjectUtil.isEmpty(comment)){
            return null;
        }else{
            return comment.getComment();
        }
    }

//    @PostMapping("addComment")
//    public Map<String,Object> addComment(@RequestBody Comment comm, HttpSession session){
//        System.out.println("0000000777777777777777777777777777777777777");
//        System.out.println(comm);
//        Map<String,Object> map = new HashMap<>();
//        User user = (User) session.getAttribute("user");
//        comm.setOrderId(user.getUserId());
//        commentService.save(comm);
//        map.put("message","success");
//        return map;
//    }

    @GetMapping("saveComment/{orderId}/{comment}")
    private String saveComment(@PathVariable(value = "comment") String comment, @PathVariable(value = "orderId") String orderId) {
        Long orderId1 = Long.parseLong(orderId);
        List<OrderItem> orderItems = orderItemService.lambdaQuery().eq(OrderItem::getOrderId, orderId1).list();
        Comment comment1 = new Comment();
        comment1.setOrderId(orderId1);
        comment1.setComment(comment);
        for (OrderItem orderItem : orderItems) {
            comment1.setPId(orderItem.getProductId());
            commentService.save(comment1);
        }
        orderService.lambdaUpdate().set(Order::getStatus, "已完成").eq(Order::getOrderId, orderId1).update();
        return "success";
    }

}
